"use client";
import * as React from "react";
import Button from "@mui/material/Button";
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  TextField,
} from "@mui/material";
import { DataGrid } from "@mui/x-data-grid";
import {
  fetchDelete,
  fetchUpdate,
  OReceive,
  MDReceive,
} from "@/components/server-fetch";

export function Datagrid(data) {
  let columns = [];
  for (let key in data.list) {
    columns.push({
      field: key,
      headerName: data.list[key]["name"],
      width: 120,
    });
  }
  const action = [
    {
      field: "action",
      headerName: "操作",
      type: "number",
      width: 128,
      renderCell: (params) => {
        // eslint-disable-next-line react-hooks/rules-of-hooks
        const [open, setOpen] = React.useState(false);

        const handleClickOpen = () => {
          setOpen(true);
        };

        const handleClose = () => {
          setOpen(false);
        };

        const handleEdit = () => {
          const postData = {};

          for (let key in data.list) {
            postData[key] = document.getElementById(key).value;
          }
          fetchUpdate(data.type, postData)
            .then((response) => response.json())
            .then((result) => {
              console.log("Success:", result);
            })
            .catch((error) => {
              console.error("Error:", error);
            });
          setOpen(false);
        };
        const handleDelete = () => {
          fetchDelete(data.type, params.row[data.keyword], data.keyword)
            .then((response) => response.json())
            .then((result) => {
              console.log("Success:", result);
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        };

        return (
          <div>
            <Button onClick={handleClickOpen}>编辑</Button>
            <Button onClick={handleDelete}>删除</Button>
            <Dialog open={open} onClose={handleClose}>
              <DialogTitle>编辑</DialogTitle>
              <DialogContent>
                <DialogContentText>编辑信息</DialogContentText>
                {Object.keys(data.list).map((key) => (
                  <TextField
                    key={key}
                    margin="dense"
                    id={key}
                    label={data.list[key]["name"]}
                    type={data.list[key]["type"]}
                    fullWidth
                    variant="standard"
                    defaultValue={params.row[key]}
                  />
                ))}
              </DialogContent>
              <DialogActions>
                <Button onClick={handleClose}>取消</Button>
                <Button onClick={handleEdit}>确认</Button>
              </DialogActions>
            </Dialog>
          </div>
        );
      },
    },
  ];
  columns.push(action[0]);

  function getRowId(row) {
    return row[data.keyword];
  }

  return (
    <DataGrid
      rows={data.rows}
      columns={columns}
      initialState={{
        pagination: {
          paginationModel: { page: 0, pageSize: 5 },
        },
      }}
      pageSizeOptions={[5, 10]}
      // checkboxSelection
      getRowId={getRowId}
    />
  );
}

export function Datagrid_t(data) {
  let columns = [];
  for (let key in data.list) {
    columns.push({
      field: key,
      headerName: data.list[key]["name"],
      width: 120,
    });
  }
  const action = [
    {
      field: "action",
      headerName: "操作",
      type: "number",
      width: 128,
      renderCell: (params) => {
        // eslint-disable-next-line react-hooks/rules-of-hooks
        const [open, setOpen] = React.useState(false);

        const handleClickOpen = () => {
          setOpen(true);
        };

        const handleClose = () => {
          setOpen(false);
        };

        const handleEdit = () => {
          const postData = {};

          for (let key in data.list2) {
            postData[key] = document.getElementById(key).value;
          }
          if (data.keyword === "materialDetailMaintenanceId") {
            MDReceive(postData["storehouseName"],postData["materialDetailMaintenanceId"]);
          }else{
            OReceive(postData["LPN"]);
          }
          setOpen(false);
        };
        const handleDelete = () => {
          fetchDelete(data.type, params.row[data.keyword], data.keyword)
            .then((response) => response.json())
            .then((result) => {
              console.log("Success:", result);
            })
            .catch((error) => {
              console.error("Error:", error);
            });
        };

        return (
          <div>
            <Button onClick={handleClickOpen}>接收</Button>
            <Button onClick={handleDelete}>删除</Button>
            <Dialog open={open} onClose={handleClose}>
              <DialogTitle>接收</DialogTitle>
              <DialogContent>
                <DialogContentText>接收信息</DialogContentText>
                {Object.keys(data.list2).map((key) => (
                  <TextField
                    key={key}
                    margin="dense"
                    id={key}
                    label={data.list2[key]["name"]}
                    type={data.list2[key]["type"]}
                    fullWidth
                    variant="standard"
                    defaultValue={params.row[key]}
                  />
                ))}
              </DialogContent>
              <DialogActions>
                <Button onClick={handleClose}>取消</Button>
                <Button onClick={handleEdit}>确认</Button>
              </DialogActions>
            </Dialog>
          </div>
        );
      },
    },
  ];
  columns.push(action[0]);

  function getRowId(row) {
    return row[data.keyword];
  }

  return (
    <DataGrid
      rows={data.rows}
      columns={columns}
      initialState={{
        pagination: {
          paginationModel: { page: 0, pageSize: 5 },
        },
      }}
      pageSizeOptions={[5, 10]}
      // checkboxSelection
      getRowId={getRowId}
    />
  );
}
